#!/bin/bash

# 部署脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== 小红书后端API部署脚本 ===${NC}"

# 检查是否以root用户运行
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}错误: 请以root用户运行此脚本${NC}"
    exit 1
fi

# 1. 创建必要的目录
echo -e "${YELLOW}1. 创建必要的目录...${NC}"
mkdir -p /path/to/media
mkdir -p /path/to/staticfiles
mkdir -p logs
chmod 755 logs

# 2. 安装依赖
echo -e "${YELLOW}2. 安装依赖...${NC}"
pip install -r requirements.txt

# 3. 配置环境变量
if [ ! -f ".env" ]; then
    echo -e "${YELLOW}3. 配置环境变量...${NC}"
    cp .env.example .env
    echo -e "${GREEN}请编辑 .env 文件，配置您的环境变量${NC}"
    echo -e "${YELLOW}按Enter键继续...${NC}"
    read
fi

# 4. 数据库迁移
echo -e "${YELLOW}4. 执行数据库迁移...${NC}"
python manage.py makemigrations
python manage.py migrate

# 5. 收集静态文件
echo -e "${YELLOW}5. 收集静态文件...${NC}"
python manage.py collectstatic --noinput

# 6. 创建超级用户（可选）
echo -e "${YELLOW}6. 是否创建Django超级用户？(y/n)${NC}"
read -r create_superuser
if [ "$create_superuser" = "y" ] || [ "$create_superuser" = "Y" ]; then
    python manage.py createsuperuser
fi

# 7. 配置Nginx
echo -e "${YELLOW}7. 配置Nginx...${NC}"
if [ -f "nginx.conf" ]; then
    cp nginx.conf /etc/nginx/conf.d/xiaohongshu_api.conf
    echo -e "${GREEN}请编辑 /etc/nginx/conf.d/xiaohongshu_api.conf 文件，修改域名和路径配置${NC}"
    nginx -t
    systemctl restart nginx
fi

# 8. 创建系统服务
echo -e "${YELLOW}8. 创建Gunicorn系统服务...${NC}"
cat > /etc/systemd/system/xiaohongshu_api.service << EOF
[Unit]
Description=Gunicorn daemon for Xiaohongshu API
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=$(pwd)
ExecStart=$(which gunicorn) -c gunicorn_config.py xiaohongshu_backend.wsgi:application
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# 9. 启动服务
echo -e "${YELLOW}9. 启动服务...${NC}"
systemctl daemon-reload
systemctl enable xiaohongshu_api
systemctl start xiaohongshu_api

# 10. 显示状态
echo -e "${YELLOW}10. 显示服务状态...${NC}"
systemctl status xiaohongshu_api --no-pager

echo -e "\n${GREEN}=== 部署完成 ===${NC}"
echo -e "${GREEN}后端API服务已启动${NC}"
echo -e "${GREEN}访问地址: https://your_domain.com${NC}"
echo -e "${GREEN}管理后台: https://your_domain.com/admin${NC}"
echo -e "\n${YELLOW}注意事项:${NC}"
echo -e "1. 请确保已在华为云安全组中开放80和443端口"
echo -e "2. 请确保SSL证书已正确配置"
echo -e "3. 请根据实际情况调整Nginx和Gunicorn配置"